package com.luojing.myThread.countdownlatch;

import java.util.concurrent.CountDownLatch;

/**
 * @author luojing
 * @create 2018/08/25 上午9:13
 *
 * 此线程描述了一个java倒数计时器的功能,必须等待计时器全部完成,任务才算完成
*  主要应用场景:多个线程下载的时候,确保所有线程全部下载完成才算完成; 或者上传文件的时候,
 *  所有线程上传完成,才算完成.主要应该是确保所有线程完成的一个计数器,但是问题可能来了,如果中间线程有的失败了,那么主线程会一直阻塞吗,不会调用await(long,unit),
 *  可以指定超时时间,getcount可以获取计数的值,判断是否完成
 **/
 class Worker implements Runnable{
  private String workerName;
  private long workTime;

  private CountDownLatch countDownLatch;

  public Worker(String workerName, CountDownLatch countDownLatch,long workTime) {
    this.workerName = workerName;
    this.countDownLatch = countDownLatch;
    this.workTime = workTime;
  }

  @Override
  public void run() {
    try {
      System.out.println("worker:" + workerName + "is running,will work:" + (workTime/1000) + "seconds");
      Thread.sleep(workTime);
      System.out.println("worker:" + workerName + "is running over");
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    countDownLatch.countDown();
  }
}
